package com.demo.filter.session;

import com.demo.wrapper.session.HttpServletRequestWrapper;
import com.demo.common.utils.CookieUtil;
import com.demo.common.utils.GlobalConstant;
import com.demo.common.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**http://blog.csdn.net/fengshizty/article/details/50578639
 * SessionFilter拦截器的实现
 */
public class SessionFilter extends OncePerRequestFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(SessionFilter.class);

//    @Autowired
    /*private  HttpServletRequestWrapper httpServletRequestWrapper=
        SpringContextHolder.getBean("httpServletRequestWrapper");*/

    public SessionFilter(){
//        log.info("--------创建 SessionFilter ......httpServletRequestWrapper = "+httpServletRequestWrapper);
        log.info("--------创建 SessionFilter ......");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        //从cookie中获取sessionId，如果此次请求没有sessionId，重写为这次请求设置一个sessionId
        String sid = CookieUtil.getCookieValue(request, GlobalConstant.JSESSIONID);
        if(StringUtil.isEmpty(sid) || sid.length() != 36){
            sid = StringUtil.getUuid();
            log.info("----sid为空创建一个新的,并把sid设置到cookie,sid = "+sid);
            CookieUtil.setCookie(request, response, GlobalConstant.JSESSIONID, sid, 60 * 60);
        }

        /*交给自定义的HttpServletRequestWrapper 改造一下
         */
//        log.info("sid = "+sid);
        filterChain.doFilter(new HttpServletRequestWrapper(sid, request, response), response);

        /*LOG.info("------过滤请求,httpServletRequestWrapper = "+httpServletRequestWrapper);
        this.httpServletRequestWrapper.setRequestResponse(sid,request,response);
        filterChain.doFilter(this.httpServletRequestWrapper, response);*/

    }
}
